package sv.com.administrador.seguros.web.security;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl;
import org.springframework.stereotype.Component;

import sv.com.administrador.seguros.dao.sgd.SgdUsuarioDao;
import sv.com.administrador.seguros.exception.WebException;
import sv.com.administrador.seguros.web.util.WebUtility;

@Component
public class CustomJdbcDaoImpl extends JdbcDaoImpl {
	private static final Logger logger = Logger.getLogger(CustomJdbcDaoImpl.class);
	
	@Resource
	private SgdUsuarioDao sgdUsuarioDao;
	
	public SgdUsuarioDao getSgdUsuarioDao() {
		return sgdUsuarioDao;
	}

	public void setSgdUsuarioDao(SgdUsuarioDao sgdUsuarioDao) {
		this.sgdUsuarioDao = sgdUsuarioDao;
	}

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		
		UserDetails user = super.loadUserByUsername(username);
		CustomUser customUser = new CustomUser(
				user.getUsername(), 
				user.getPassword(), 
				user.isEnabled(),user.isAccountNonExpired(), 
				user.isCredentialsNonExpired(), 
				user.isAccountNonLocked(), 
				user.getAuthorities());
		try {
			customUser.setSgdUsuario(sgdUsuarioDao.findBySgdUsuarioUsuario(username));
		} catch (WebException e) {
			logger.error(e, e);
			throw new UsernameNotFoundException(WebUtility.getExceptionMessage(e));
		}
		return customUser;
	}
	
}
